package com.riche.codefactory.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riche.codefactory.annotation.AuthCheck;
import com.riche.codefactory.common.BaseResponse;
import com.riche.codefactory.common.DeleteRequest;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.common.R;
import com.riche.codefactory.config.WxOpenConfig;
import com.riche.codefactory.constant.UserConstant;
import com.riche.codefactory.exception.BusinessException;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.model.c2s.user.*;
import com.riche.codefactory.model.domain.User;
import com.riche.codefactory.model.s2c.S2cLoginUser;
import com.riche.codefactory.model.s2c.S2cUser;
import com.riche.codefactory.service.IUserSVC;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.riche.codefactory.service.impl.UserSVC.SALT;

/**
 * 用户接口
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserSVC userService;

    @Resource
    private WxOpenConfig wxOpenConfig;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param c2sUserRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody C2sUserRegisterRequest c2sUserRegisterRequest) {
        if (c2sUserRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = c2sUserRegisterRequest.getUserAccount();
        String userPassword = c2sUserRegisterRequest.getUserPassword();
        String checkPassword = c2sUserRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return R.ok(result);
    }

    /**
     * 用户登录
     *
     * @param c2sUserLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<S2cLoginUser> userLogin(@RequestBody C2sUserLoginRequest c2sUserLoginRequest, HttpServletRequest request) {
        if (c2sUserLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = c2sUserLoginRequest.getUserAccount();
        String userPassword = c2sUserLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        S2cLoginUser s2cLoginUser = userService.userLogin(userAccount, userPassword, request);
        return R.ok(s2cLoginUser);
    }

    /**
     * 用户登录（微信开放平台）
     */
    @GetMapping("/login/wx_open")
    public BaseResponse<S2cLoginUser> userLoginByWxOpen(HttpServletRequest request, HttpServletResponse response,
                                                        @RequestParam("code") String code) {
        WxOAuth2AccessToken accessToken;
        try {
            WxMpService wxService = wxOpenConfig.getWxMpService();
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
            String unionId = userInfo.getUnionId();
            String mpOpenId = userInfo.getOpenid();
            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
            }
            return R.ok(userService.userLoginByMpOpen(userInfo, request));
        } catch (Exception e) {
            log.error("userLoginByWxOpen error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return R.ok(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<S2cLoginUser> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return R.ok(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param c2sUserAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody C2sUserAddRequest c2sUserAddRequest, HttpServletRequest request) {
        if (c2sUserAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(c2sUserAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return R.ok(b);
    }

    /**
     * 更新用户
     *
     * @param c2sUserUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody C2sUserUpdateRequest c2sUserUpdateRequest,
                                            HttpServletRequest request) {
        if (c2sUserUpdateRequest == null || c2sUserUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(c2sUserUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return R.ok(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<S2cUser> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return R.ok(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param c2sUserQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody C2sUserQueryRequest c2sUserQueryRequest,
                                                   HttpServletRequest request) {
        long current = c2sUserQueryRequest.getCurrent();
        long size = c2sUserQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(c2sUserQueryRequest));
        return R.ok(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param c2sUserQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<S2cUser>> listUserVOByPage(@RequestBody C2sUserQueryRequest c2sUserQueryRequest,
                                                        HttpServletRequest request) {
        if (c2sUserQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = c2sUserQueryRequest.getCurrent();
        long size = c2sUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(c2sUserQueryRequest));
        Page<S2cUser> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<S2cUser> s2cUser = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(s2cUser);
        return R.ok(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param c2sUserUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody C2sUserUpdateMyRequest c2sUserUpdateMyRequest,
                                              HttpServletRequest request) {
        if (c2sUserUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(c2sUserUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 添加用户签到记录
     *
     * @return 当前用户是否签到成功
     */
    @PostMapping("/add/sign_in")
    public BaseResponse<Boolean> addUserSignIn(HttpServletRequest request) {
        // todo 可以改为异步签到登录
        // 必须要登录才能签到
        User loginUser = userService.getLoginUser(request);
        boolean result = userService.addUserSignIn(loginUser.getId());
        return R.ok(result);
    }


    /**
     * 获取用户签到记录
     *
     * @return 当前用户是否签到成功
     */
    @GetMapping("/get/sign_in")
    public BaseResponse<List<Integer>> getUserSignInRecord(Integer year, HttpServletRequest request) {
        // 必须登录才能进行获取
        User loginUser = userService.getLoginUser(request);
        List<Integer> userSignInRecord = userService.getUserSignInRecord(loginUser.getId(), year);
        return R.ok(userSignInRecord);

    }
}
